package come.itheima.springbootwebmybatistlias.service.impl;


import come.itheima.springbootwebmybatistlias.mapper.DeptMapper;
import come.itheima.springbootwebmybatistlias.mapper.EmpMapper;
import come.itheima.springbootwebmybatistlias.pojo.Dept;
import come.itheima.springbootwebmybatistlias.pojo.DeptLog;
import come.itheima.springbootwebmybatistlias.service.DeptLogService;
import come.itheima.springbootwebmybatistlias.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private DeptLogService deptLogService;

    //查询部门
    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }

    //删除部门
    @Override
    @Transactional//事务管理
    public void delete(Integer id) throws Exception{
        try {
            //根据ID删除部门数据
            deptMapper.deleteById(id);

            //int i = 1/0;//模拟异常

            //根据部门id删除员工数据
            empMapper.deleteByDeptId(id);


        } finally {
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行了解散部门的操作，解散"+id+"号部门");
            deptLogService.insert(deptLog);
        }

    }

    //新增部门
    @Override
    public void add(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insert(dept);
    }

    //根据id查询部门
    @Override
    public Dept queryDeptById(Integer id) {
        return deptMapper.queryDeptById(id);

    }


    //修改部门
    @Override
    public void modifyDept(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.modifyDept(dept);
    }





}